package com.zhou.cloud.service.impl;

import com.zhou.cloud.service.IMongodbPersonService;
import com.zhou.cloud.dao.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @descrition:
 * @author: zhouyongjun
 * @date: 2022/7/21
 **/
@Service
public class MongodbPersonServiceImpl implements IMongodbPersonService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public int insert(Person person) {
        try {
            person.setTimer(LocalDateTime.now());
            mongoTemplate.insert(person);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int update(Person person) {
        //通过query根据id查询出对应对象，通过update对象进行修改
        Query query = new Query(Criteria.where("_id").is(person.getId()));
        Update update = new Update().set("username", person.getUsername());
        try {
            mongoTemplate.updateFirst(query, update, Person.class);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int remove(Long id) {
        Query query=new Query(Criteria.where("_id").is(id));
        try {
            mongoTemplate.remove(query,Person.class);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public Person find(Long id) {
        Query query = new Query(Criteria.where("_id").is(id));
        Person one = mongoTemplate.findOne(query, Person.class);
        return one;
    }

    @Override
    public List<Person> findAll() {
        Query query = new Query();
        List<Person> studentList = mongoTemplate.find(query, Person.class);
        return studentList;
    }

    @Override
    public List<Person> findlike(String name) {
        Pattern pattern = Pattern.compile("^.*" + name.trim() + ".*$", Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("username").regex(pattern));
        List<Person> studentList = mongoTemplate.find(query, Person.class);
        return studentList;
    }

    @Override
    public List<Person> findtime() {
        Query query = new Query();
//        query.with(new Sort(Sort.Direction.DESC, "timer"));
        List<Person> students = mongoTemplate.find(query, Person.class);
        return students;
    }
}
